﻿using System;
using System.Windows.Threading;

namespace NB_Controller_Test
{
    class TimerProc
    {
        public delegate Boolean TimerCallBackFun(Object arg);

        private DispatcherTimer mTimeDispatch;
        private TimerCallBackFun timerCallBackFun;
        private Object mObjArg;

        public TimerProc()
        {
            mTimeDispatch = new DispatcherTimer();
        }

        public static Boolean StartTimerTask(TimerCallBackFun timerCallBack, Object objArg, Boolean rightNow, Int32 nIntervelMs)
        {
            TimerProc timer = new TimerProc();
            timer.mTimeDispatch = new DispatcherTimer();
            timer.mTimeDispatch.Interval = TimeSpan.FromMilliseconds(nIntervelMs);
            timer.mTimeDispatch.Tick += new EventHandler(timer.DispatcherTimerHandler);
            timer.timerCallBackFun = timerCallBack;
            timer.mObjArg = objArg;

            Boolean bRet = true;
            if (rightNow)
            {
                bRet = timer.timerCallBackFun(timer.mObjArg);
            }
            //启动定时
            timer.mTimeDispatch.Start();

            return bRet;
        }
        
        private void DispatcherTimerHandler(object sender, EventArgs e)
        {
            Boolean bRet = timerCallBackFun(this.mObjArg);

            if (!bRet)
            {
                mTimeDispatch.Stop();
                mTimeDispatch = null;
            }
        }        
    }
}
